//
//  HMComposeViewController.swift
//  WeiBoSwift
//
//  Created by hgj on 2016/11/21.
//  Copyright © 2016年 HuGuoJian. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white
        
        setupNavBar()
        
        
        setupTextView()

        setupSelectPicView()
        setupToolBar()
        
        view.bringSubview(toFront: toolBar)
        
        registerNotification()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        selectePicVC.view.isHidden = selectePicVC.images.count == 0
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    private func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        // 注册表情选中的通知
        NotificationCenter.default.addObserver(self, selector: #selector(inputEmoticon(noti:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
    }
    
    @objc private func keyboardWillChange(noti: Notification) {
        let endFrame = noti.userInfo?[UIKeyboardFrameEndUserInfoKey] as! CGRect
        let offsetY = -ScreenHeight + endFrame.origin.y
       
        UIView.animate(withDuration: 0.25, animations:{
            // 更新约束
            self.toolBar.snp.updateConstraints { (make) in
                make.bottom.equalTo(offsetY)
            }
        })
        view.layoutIfNeeded()
    }
    
    @objc private func inputEmoticon(noti: Notification) {
        guard let em = noti.object as? HMEmoticon else {
        
            // 点击的是删除按钮  这里noti.object==nil 执行回删操作
            textView.deleteBackward()
            return
        }
        
        // emoj表情
        if em.type == 1 {
            //textView.selectedTextRange 表示的是光标选择的地方,替换成emojy表情
            textView.replace(textView.selectedTextRange!, withText: em.emojiStr!)
            return
        }
        
        // 图片表情
        textView.inputEmoticon(em: em)
    }
    
    // 要调用,主要是规范
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    @objc fileprivate func close(item: UIBarButtonItem) {
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func sendBtnDidClick() {
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        let parameters = ["access_token" : HMUserAccountViewModel.shared.userInfo?.access_token,
                          "status" : textView.imageEmoticon2Chs()]
        SVProgressHUD.show()
        if selectePicVC.images.count == 0 {
            HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters, finished: { (_, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发布微博失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发布微博成功")
                return
            })
            
        } else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            HMNetworkTools.shared.post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
                let imageData = UIImagePNGRepresentation(self.selectePicVC.images.first!)
                formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "gg", mimeType: "application/octet-stream")
            }, progress: nil, success: { (_, _) in
                SVProgressHUD.showSuccess(withStatus: "发布微博成功")
            }, failure: { (_, error) in
                SVProgressHUD.showError(withStatus: "发布微博失败")
            })
        }
        
    }
    
    @objc private func statueTypeBtnDidClick(btn: UIButton) {
        
        switch btn.tag {
        case 0:
            print("发布图片")
            //手动调用协议方法
            selectePicVC.userWillAddPic()
        case 1:
            print("@某人")
        case 2:
            print("发布话题")
        case 3:
            print("发送表情")
            //使用自定义键盘
            // 自定义键盘就是使用inputView
            //系统键盘已经是第一响应者的时候是无法进行替换的
            //当输入视图是系统键盘的时候 inputView的值为nil  为nil的情况下系统会自动弹出系统键盘
            if !textView.isFirstResponder {
                //不是第一响应者
                //成为第一响应者
                textView.becomeFirstResponder()
            }
            textView.inputView = (textView.inputView == nil ? keyboardView : nil)
            textView.reloadInputViews()// 刷新一下
        case 4:
            print("更多")
        default:
            print("瞎点")
        }
    }
    
    //表情键盘视图声明为属性
    lazy var keyboardView: HMEmoticonKeyboardView = {
        //在iPhone plus类型的设备上键盘的高度 是226 其他的设备都是216
        let keyboard = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: emoticonKeyboardHeight))
        
        return keyboard
    }()
    
    
    // 懒加载微博发布按钮
    lazy var senBtn: UIBarButtonItem = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        //设置文字
        btn.setTitle("发送", for: .normal)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.addTarget(self, action: #selector(sendBtnDidClick), for: .touchUpInside)
        
        // 自定义视图
        let barButtonItem = UIBarButtonItem(customView: btn)
        // 默认是禁用的
        barButtonItem.isEnabled = false
        return barButtonItem
    }()
    
    // 加载textview
    lazy var textView: HMEmoticonTextView = {
        let tv = HMEmoticonTextView()
        tv.text = ""
        tv.backgroundColor = UIColor.darkGray
        tv.font = UIFont.systemFont(ofSize: 18)
        
        // 代理
        tv.delegate = self
        
//        tv.keyboardDismissMode = .onDrag
        tv.alwaysBounceVertical = true
        
        return tv
    }()
    
    // 占位文本
    fileprivate lazy var palceHodelrLabel: UILabel = UILabel(title: "小鸡吧,快来发个微博吧", titleColor: UIColor.lightGray, fontSize: 18)

    fileprivate lazy var toolBar: UIToolbar = {
       let tool = UIToolbar()
        var items: [UIBarButtonItem] = [UIBarButtonItem]()
        // 添加五个按钮
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        for value in imageNames.enumerated() {
            let btn = UIButton()
            btn.setImage(UIImage(named: value.element), for: .normal)
            btn.setImage(UIImage(named: value.element), for: .selected)
            
            btn.tag = value.offset
            // 添加点击事件
            btn.addTarget(self, action: #selector(statueTypeBtnDidClick(btn:)), for: .touchUpInside)
            btn.sizeToFit()
            // 自定义视图
            let barItem = UIBarButtonItem(customView: btn)
            items.append(barItem)
            
            let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        tool.items = items // tool
        return tool
    }()
    
    // 图片选中视图控制器
    lazy var selectePicVC: HMPicSelectViewController = {
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumLineSpacing = selectCellMargin
        layout.minimumInteritemSpacing = selectCellMargin
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.sectionInset = UIEdgeInsets(top: selectCellMargin, left: selectCellMargin, bottom: 0, right: selectCellMargin)
     
        let selectVC = HMPicSelectViewController(collectionViewLayout: layout)
            //UICollectionViewController(collectionViewLayout: <#T##UICollectionViewLayout#>)
        selectVC.collectionView?.backgroundColor = UIColor.white
        return selectVC
    }()
}



extension HMComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        self.senBtn.isEnabled = textView.hasText
        self.palceHodelrLabel.isHidden = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
}

extension HMComposeViewController {
    
    // 1.设置navBar
    fileprivate func setupNavBar() {
        
        // 1.设置关闭按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close(item:)))
        
        // 2.设置中间视图
        let titleLabel = UILabel(title: "", titleColor: UIColor.gray, fontSize: 16)
        
        
        // 设置标题
        var titleText = "发布微博"
        
        // 设置属性
        titleLabel.numberOfLines = 0
        titleLabel.textAlignment = .center
        
        // 用if判断的原因可能读取不到用户的名字(读取和未读取)
        if let name = HMUserAccountViewModel.shared.userInfo?.name {
            
            titleText = "发布微博\n\(name)"
            
            // 这里正只能通过富文本来修改文字的颜色和字体
            // 实例化一个可变属性文本
            let mAttStr = NSMutableAttributedString(string: titleText)
            let range = (titleText as NSString).range(of: name)
            
            // 给可变属性字符串添加属性
            mAttStr.addAttributes([NSForegroundColorAttributeName : UIColor.orange,NSFontAttributeName : UIFont.systemFont(ofSize: 13)], range: range)
            // 设置属性字符串
            titleLabel.attributedText = mAttStr
        } else  {
            titleLabel.text = titleText
        }
        titleLabel.sizeToFit()
        navigationItem.titleView = titleLabel
        
        
        // 3.设置微博发布按钮
        //        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", target: self, action: #selector(clickSendButton(item:)
        //            ))
        navigationItem.rightBarButtonItem = senBtn
    }
    
    // 2. 设置textView
    fileprivate func setupTextView() {
        view.addSubview(textView)
        textView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(view)
            make.height.equalTo(ScreenHeight/3)
        }
        textView.addSubview(palceHodelrLabel)
        palceHodelrLabel.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
    }
    
    // 3. 设置图片选择视图
    fileprivate func setupSelectPicView() {
        addChildViewController(selectePicVC)
        view.addSubview(selectePicVC.view)
        
        selectePicVC.view.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(view)
            make.height.equalTo(ScreenHeight / 3 * 2)
        }
        selectePicVC.view.isHidden = true
    }
    
    // 4. 设置toolBar
    fileprivate func setupToolBar() {
        view.addSubview(toolBar)
        toolBar.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(36)
        }
    }
}
